#!/bin/env/python3
import datetime
import json
import random
import re

from flask import request, current_app, make_response, jsonify, session

from . import passport_blue

from info.utils.captcha.captcha import captcha

from ... import redis_store, constants, db
from ...libs.sms import sendcode
from ...models import User
from ...utils.response_code import RET


# 退出登录
@passport_blue.route('/logout', methods=['POST'])
def logout():
    session.pop("user_id", None)
    session.pop("is_admin", None)
    return jsonify(errno=RET.OK, errmsg="退出成功")


# 登录
@passport_blue.route('/login', methods=['GET', 'POST'])
def login():
    dict_data = request.json
    tel = dict_data.get("mobile")
    password = dict_data.get("password")
    # 检验参数
    if not all([tel, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    #  读取用户
    try:
        user = db.session.query(User).filter(User.mobile == tel).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户失败")
    # 判断用户
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")
    # 判断密码
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="用户名或密码错误")
    # 将用户信息保存在session中
    session["user_id"] = user.id

    # 记录用户的最后登录时间
    user.last_login = datetime.datetime.now()

    return jsonify(errno=RET.OK, errmsg="登录成功")


# 注册
@passport_blue.route('/register', methods=['GET', 'POST'])
def register():
    # json_data = request.data
    # dict_data = json.loads(json_data)
    dict_data = request.json
    tel = dict_data.get("mobile")
    code = dict_data.get("sms_code")
    password = dict_data.get("password")
    if not all([tel, code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        if redis_store.get(tel) != code:
            return jsonify(errno=RET.DATAERR, errmsg="验证码错误")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="判断验证码失败")
    try:
        redis_store.delete(tel)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="删除验证码失败")
    user = User()
    user.nick_name = tel
    user.password = password
    user.mobile = tel
    user.signature = "什么都没写"
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="用户注册失败")
    return jsonify(errno=RET.OK, errmsg="注册成功")


@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():
    # 获取参数
    # json_data = request.data
    # dict_data = json.loads(json_data)
    # 可以替换掉上面的两句
    # dict_data  = request.get_json()
    dict_data = request.json
    tel = dict_data.get("mobile")
    image_text = dict_data.get("image_code")
    image_id = dict_data.get("image_code_id")
    if not all([image_text, tel, image_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 参数校验:
    if not re.match(r"1[3-9]\d{9}", tel):
        return jsonify(errno=RET.DATAERR, errmsg="手机号格式不正确")
    # 获取图片验证码
    try:
        redis_image_code = redis_store.get("image_code:%s" % image_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="操作redis失败")

    # 判断图片验证码是否过期
    if not redis_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码失效/过期")

    # 判断图片验证码是否正确:
    print(image_text)
    print(redis_image_code.upper())
    if redis_image_code != image_text.upper():
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误")

    # 删除redis中的图片验证码
    try:
        redis_store.delete("imgae_code:%s" % image_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="删除redis图片验证码失败")

    # 发送/短信发送状态校验:
    try:
        if sendcode(tel):
            return jsonify(errno=777, errmsg="短信发送失败")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证失败")
    return jsonify(errno=RET.OK, errmsg="短信发送成功")


# 获取图片验证码
@passport_blue.route('/image_code')
def image_code():
    # 获取前端传递的参数
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    name, text, image_data = captcha.generate_captcha()
    # 将图片验证码的值保存redis
    try:
        redis_store.set("image_code:%s" % cur_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
        if pre_id:
            redis_store.delete("image_code:%s" % pre_id)
    except Exception as e:
        current_app.logger.error(e)
        return "图片验证码操作失败"
    # 返回图片 src标签会将二进制数据转成图片
    response = make_response(image_data)
    response.headers["ContentType"] = "image/png"
    return response
